package cn.util.shiro;

import org.apache.shiro.config.Ini;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.util.CollectionUtils;
import org.apache.shiro.web.config.IniFilterChainResolverFactory;

import java.util.List;
import java.util.Map;

/**
 * Shiro 过滤链 定义  从数据库动态加载
 *
 * 重写 Shiro ShiroFilterFactoryBean过滤器
 */
// 不需要@Component("shiroFilterChain")，因为xml文件实例化了
public class ShiroFilter extends ShiroFilterFactoryBean {
    /**配置中的过滤链*/
    public static String definitions;
    //数据库的动态过滤链
    public  String sqlinitions;
    /**
     * 首次启动 Shiro加载
     * @param definitions
     */
    public void setFilterChainDefinitions(String definitions) {
           ShiroFilter.definitions = definitions;
        //从配置文件加载权限配置
        Ini ini = new Ini();
        ini.load(definitions);
        Ini.Section section = ini.getSection(IniFilterChainResolverFactory.URLS);
        if (CollectionUtils.isEmpty(section)) {
            section = ini.getSection(Ini.DEFAULT_SECTION_NAME);
        }
        //加入权限集合
        setFilterChainDefinitionMap(section);
    }
    /**
     * 从数据库动态读取权限
     */
    public void ShiroInit(List<Map<String,Object>> shirourl){
        //数据库动态权  字符串拼接权限
        for (Map<String,Object> map:shirourl){
            sqlinitions = sqlinitions+map.get("SHIRO_URL") + " = "+map.get("SHIRO_POWER")+"\n\t\t\t";
        }
        //从配置文件加载权限配置
        Ini ini = new Ini();
        ini.load(definitions+sqlinitions);
        Ini.Section section = ini.getSection(IniFilterChainResolverFactory.URLS);
        if (CollectionUtils.isEmpty(section)) {
            section = ini.getSection(Ini.DEFAULT_SECTION_NAME);
        }
        //加入权限集合
        setFilterChainDefinitionMap(section);
    }
}
